package com.dd.cloud.gateway.config;

import com.dd.cloud.gateway.properties.CorsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.List;

/**
 * @Description: 跨域配置
 * @Author: czg
 * @Date: 2022/12/2 18:10
 * @Version: 1.0.0
 */
@Configuration
@EnableConfigurationProperties(CorsProperties.class)
@Slf4j
@ConditionalOnProperty(name = "dadao.cors.enable", havingValue = "true")
// 配置条件生效，当application.yml中包含zkop.cors.enable=true配置时生效，不存在时，该配置不会被Spring加载
public class CorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter(CorsProperties cors){
        CorsConfiguration config = new CorsConfiguration();
        List<String> origins = cors.getOrigins();
        if (origins != null) {
            for (int i = 0; i < origins.size(); i++) {
                String string = origins.get(i);
                // 1.添加CORS配置信息
                // 1) 允许的域,不要写*，否则cookie就无法使用了
                config.addAllowedOrigin(string);
            }
        }
        List<String> allowedOrigins = config.getAllowedOrigins();
        log.info("公共允许跨域的域名：{}", allowedOrigins);
        // 2) 是否发送Cookie信息
        config.setAllowCredentials(true);
        // 3) 允许的请求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        // 4）允许的头信息
        config.addAllowedHeader("*");
        // 5) 有效时长
        // config.setMaxAge(3600L);

        // 2.添加映射路径，我们拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        // 3.返回新的CorsFilter.
        return new CorsWebFilter(source);

    }
}
